import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'dart:developer' as developer;
import 'package:google_fonts/google_fonts.dart';
import '../models/word.dart';
import '../services/database_service.dart';
import '../utils/word_import_export_util.dart';
import 'add_edit_word_screen.dart';
import 'word_import_export_screen.dart';

class WordListScreen extends StatefulWidget {
  const WordListScreen({super.key});

  @override
  State<WordListScreen> createState() => _WordListScreenState();
}

class _WordListScreenState extends State<WordListScreen> with WidgetsBindingObserver {
  List<Word> _words = [];
  List<Word> _filteredWords = []; // 用于存储搜索过滤后的单词
  bool _isLoading = true;
  String _errorMessage = '';
  String _statusMessage = '';
  
  // 搜索相关
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';
  
  // 多选模式相关状态
  bool _isMultiSelectMode = false;
  Set<int> _selectedWordIds = {}; // 存储选中的单词ID

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _searchController.addListener(_filterWords);
    _loadWords();
  }
  
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadWords();
  }
  
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _loadWords();
    }
  }
  
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _searchController.removeListener(_filterWords);
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadWords() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = '';
        _filteredWords = []; // 清空过滤列表
      });

      developer.log('开始加载单词列表');
      final databaseService = DatabaseService();
      await databaseService.init();
      developer.log('数据库初始化完成');

      // 检查数据库中单词表的数量
      final count = await databaseService.wordRepository.getWordCount();
      developer.log('数据库中单词数量: $count');

      final words = await databaseService.wordRepository.getAllWords();
      developer.log('成功加载单词列表，共 ${words.length} 个单词');
      
      // 打印所有单词的详细信息
      for (var word in words) {
        developer.log('单词: ${word.word}, 翻译: ${word.translation}, ID: ${word.id}');
      }

      if (mounted) {
        setState(() {
          _words = words;
          _isLoading = false;
          _filterWords(); // 应用搜索过滤
        });
      }
    } catch (e) {
      developer.log('加载单词列表失败: $e', error: e);
      if (mounted) {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载单词列表失败: $e';
        });
      }
    }
  }

  Future<void> _deleteWord(Word word) async {
    try {
      developer.log('准备删除单词: ${word.word}, ID: ${word.id}');
      final databaseService = DatabaseService();
      await databaseService.init();
      await databaseService.wordRepository.deleteWord(word.id!);
      developer.log('单词删除成功');

      // 重新加载单词列表
      _loadWords();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('单词删除成功'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      developer.log('删除单词失败: $e', error: e);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除单词失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
  
  // 批量删除单词的方法
  Future<void> _batchDeleteWords() async {
    try {
      developer.log('准备批量删除单词，数量: ${_selectedWordIds.length}');
      final databaseService = DatabaseService();
      await databaseService.init();
      
      int successCount = 0;
      for (final id in _selectedWordIds) {
        final success = await databaseService.wordRepository.deleteWord(id);
        if (success) successCount++;
      }
      
      developer.log('批量删除完成，成功: $successCount/${_selectedWordIds.length}');

      // 清空选中状态并退出多选模式
      setState(() {
        _selectedWordIds.clear();
        _isMultiSelectMode = false;
      });
      
      // 重新加载单词列表
      _loadWords();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('成功删除 $successCount 个单词'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      developer.log('批量删除单词失败: $e', error: e);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('批量删除失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
  
  // 导出单词到CSV文件
  Future<void> _exportWords() async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      developer.log('准备导出单词，数量: ${_words.length}');
      
      // 如果是多选模式且有选中的单词，则只导出选中的单词
      List<Word> wordsToExport = [];
      if (_isMultiSelectMode && _selectedWordIds.isNotEmpty) {
        wordsToExport = _words.where((word) => _selectedWordIds.contains(word.id)).toList();
        developer.log('导出选中的单词，数量: ${wordsToExport.length}');
      } else {
        wordsToExport = _words;
        developer.log('导出所有单词，数量: ${wordsToExport.length}');
      }
      
      final filePath = await WordImportExportUtil.exportWordsToCSV(wordsToExport);
      
      setState(() {
        _isLoading = false;
      });
      
      if (mounted) {
        if (filePath != null) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('成功导出 ${wordsToExport.length} 个单词\n保存路径: $filePath', style: const TextStyle(fontFamily: 'FangSong')),
              duration: const Duration(seconds: 5),
              backgroundColor: Colors.green,
            ),
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('导出单词失败', style: TextStyle(fontFamily: 'FangSong')),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      developer.log('导出单词失败: $e', error: e);
      setState(() {
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('导出单词失败: $e', style: const TextStyle(fontFamily: 'FangSong')),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
  
  // 导入单词
  Future<void> _importWords() async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      developer.log('准备导入单词');
      
      // 从CSV或Excel文件导入单词
      final importResult = await WordImportExportUtil.importWordsFromCSVOrExcel();
      developer.log('从CSV或Excel文件导入的单词数量: ${importResult.words.length}，错误数量: ${importResult.errors.length}');
      
      // 批量添加单词到数据库
      final databaseService = DatabaseService();
      await databaseService.init();
      final successCount = await databaseService.wordRepository.addWords(importResult.words);
      
      developer.log('成功导入 $successCount/${importResult.words.length} 个单词');
      
      // 重新加载单词列表
      _loadWords();
      
      setState(() {
        _isLoading = false;
      });
      
      if (mounted) {
        // 如果有错误，显示带有警告的消息
        if (importResult.hasErrors) {
          _showImportResultDialog(
            title: '导入部分成功',
            content: '成功导入 $successCount/${importResult.words.length} 个单词，但有以下问题：\n\n${importResult.errors.join('\n')}',
            isError: false
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('成功导入 $successCount/${importResult.words.length} 个单词', style: const TextStyle(fontFamily: 'FangSong')),
              backgroundColor: Colors.green,
            ),
          );
        }
      }
    } catch (e) {
      developer.log('导入单词失败: $e', error: e);
      setState(() {
        _isLoading = false;
      });
      if (mounted) {
        // 显示更详细的错误信息
        final errorMessage = e.toString();
        // 检查是否包含多行错误信息（导入时的行错误）
        if (errorMessage.contains('\n')) {
          _showImportResultDialog(
            title: '导入失败',
            content: errorMessage.replaceAll('Exception: ', ''),
            isError: true
          );
        } else {
          // 使用Snackbar显示简单错误信息
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('导入单词失败: ${errorMessage.replaceAll('Exception: ', '')}', style: const TextStyle(fontFamily: 'FangSong')),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    }
  }
  
  // 显示导入结果对话框
  void _showImportResultDialog({required String title, required String content, required bool isError}) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title, style: const TextStyle(fontFamily: 'FangSong')),
        content: SingleChildScrollView(
          child: Text(content, style: const TextStyle(fontFamily: 'FangSong')),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定', style: TextStyle(fontFamily: 'FangSong')),
          ),
        ],
        backgroundColor: isError ? Colors.red[50] : Colors.amber[50],
      ),
    );
  }

  // 创建示例单词数据
  Future<void> _createSampleWords() async {
    final sampleWords = [
      Word(
        word: 'apple',
        translation: '苹果',
        pronunciation: '/ˈæpl/',
        meaning: 'a round fruit with red, yellow, or green skin and firm white flesh',
        example: 'I eat an apple every day.',
        category: '水果',
        difficulty: 1,
      ),
      Word(
        word: 'banana',
        translation: '香蕉',
        pronunciation: '/bəˈnɑːnə/',
        meaning: 'a long curved fruit with a yellow skin and soft sweet flesh',
        example: 'Monkeys love to eat bananas.',
        category: '水果',
        difficulty: 1,
      ),
      Word(
        word: 'computer',
        translation: '电脑',
        pronunciation: '/kəmˈpjuːtər/',
        meaning: 'an electronic device for storing and processing data',
        example: 'I use my computer to write emails.',
        category: '科技',
        difficulty: 2,
      ),
      Word(
        word: 'algorithm',
        translation: '算法',
        pronunciation: '/ˈælɡərɪðəm/',
        meaning: 'a process or set of rules to be followed in calculations or other problem-solving operations',
        example: 'Sorting algorithms are fundamental in computer science.',
        category: '科技',
        difficulty: 3,
      ),
      Word(
        word: 'democracy',
        translation: '民主',
        pronunciation: '/dɪˈmɒkrəsi/',
        meaning: 'a system of government by the whole population or all eligible members of a state',
        example: 'The country has been a democracy since 1945.',
        category: '政治',
        difficulty: 3,
      ),
    ];
    
    setState(() {
      _statusMessage = '已创建${sampleWords.length}个示例单词';
    });
    
    // 询问用户是否要保存到数据库
    final shouldSave = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('保存到数据库', style: TextStyle(fontFamily: 'FangSong')),
          content: const Text('是否将示例单词保存到数据库？', style: TextStyle(fontFamily: 'FangSong')),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('确定', style: TextStyle(fontFamily: 'FangSong')),
            ),
          ],
        ),
      ) ?? false;
    
    if (shouldSave) {
      try {
        final databaseService = DatabaseService();
        await databaseService.init();
        final successCount = await databaseService.wordRepository.addWords(sampleWords);
        
        developer.log('成功保存 $successCount/${sampleWords.length} 个示例单词');
        
        // 重新加载单词列表
        _loadWords();
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('成功保存 $successCount/${sampleWords.length} 个示例单词', style: const TextStyle(fontFamily: 'FangSong')),
              backgroundColor: Colors.green,
            ),
          );
        }
      } catch (e) {
        developer.log('保存示例单词失败: $e', error: e);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('保存示例单词失败: $e', style: const TextStyle(fontFamily: 'FangSong')),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    }
  }

  // 导航到单词导入导出页面
  Future<void> _showImportExportDialog() async {
    // 获取当前列表的单词数据
    List<Word> wordsToExport = [];
    if (_isMultiSelectMode && _selectedWordIds.isNotEmpty) {
      // 如果是多选模式且有选中的单词，则只传递选中的单词
      wordsToExport = _words.where((word) => _selectedWordIds.contains(word.id)).toList();
    } else {
      // 否则传递当前所有单词
      wordsToExport = _words;
    }
    
    // 使用context.push导航，这样会保持底部导航栏
    final result = await context.push<bool>(
      '/word-import-export',
      extra: wordsToExport,
    );
    
    // 如果返回结果为true，表示需要刷新单词列表
    if (result == true) {
      _loadWords();
    }
  }

  // 过滤单词列表的方法
  void _filterWords() {
    final query = _searchController.text.toLowerCase().trim();
    setState(() {
      _searchQuery = query;
      if (query.isEmpty) {
        _filteredWords = List.from(_words);
      } else {
        _filteredWords = _words.where((word) {
          return word.word.toLowerCase().contains(query) ||
              (word.translation != null && word.translation!.toLowerCase().contains(query)) ||
              (word.meaning != null && word.meaning!.toLowerCase().contains(query)) ||
              (word.category != null && word.category!.toLowerCase().contains(query));
        }).toList();
      }
    });
  }

  // 显示批量删除确认对话框
  void _showBatchDeleteConfirmDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认批量删除', style: TextStyle(fontFamily: 'FangSong')),
        content: Text('确定要删除选中的 ${_selectedWordIds.length} 个单词吗？', style: const TextStyle(fontFamily: 'FangSong')),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _batchDeleteWords();
            },
            child: const Text('删除', style: TextStyle(fontFamily: 'FangSong')),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('单词列表', style: TextStyle(fontFamily: 'FangSong')),
        actions: [
          // 卡片记忆练习按钮
          TextButton.icon(
            icon: const Icon(Icons.credit_card),
            label: const Text('卡片记忆', style: TextStyle(fontFamily: 'FangSong')),
            onPressed: () => context.go('/word-list/card-memory'),
          ),
          // 导入导出按钮
          IconButton(
            icon: const Icon(Icons.import_export),
            tooltip: '单词导入导出',
            onPressed: _showImportExportDialog,
            iconSize: 24,
          ),
          // 多选模式下显示全选按钮
          if (_isMultiSelectMode)
            IconButton(
              icon: const Icon(Icons.select_all),
              onPressed: () {
                setState(() {
                  // 如果当前已经全选，则取消全选
                  if (_selectedWordIds.length == _words.length) {
                    _selectedWordIds.clear();
                  } else {
                    // 否则全选所有单词
                    _selectedWordIds = _words.where((word) => word.id != null)
                        .map((word) => word.id!)
                        .toSet();
                  }
                });
              },
              tooltip: _selectedWordIds.length == _words.length ? '取消全选' : '全选',
              iconSize: 24,
            ),
          // 多选模式下显示批量删除按钮
          if (_isMultiSelectMode && _selectedWordIds.isNotEmpty)
            IconButton(
              icon: const Icon(Icons.delete, color: Colors.red),
              onPressed: _showBatchDeleteConfirmDialog,
              tooltip: '批量删除',
              iconSize: 24,
            ),
          // 多选模式切换按钮
          IconButton(
            icon: Icon(_isMultiSelectMode ? Icons.cancel : Icons.select_all),
            onPressed: () {
              setState(() {
                _isMultiSelectMode = !_isMultiSelectMode;
                // 退出多选模式时清空选择
                if (!_isMultiSelectMode) {
                  _selectedWordIds.clear();
                }
              });
            },
            tooltip: _isMultiSelectMode ? '取消多选' : '多选',
            iconSize: 24,
          ),
        ],
      ),
      body: Column(
        children: [
          // 搜索框
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: '搜索单词、释义、分类...',
                hintStyle: const TextStyle(fontFamily: 'FangSong'),
                prefixIcon: const Icon(Icons.search),
                suffixIcon: _searchQuery.isNotEmpty
                    ? IconButton(
                        icon: const Icon(Icons.clear),
                        onPressed: () {
                          _searchController.clear();
                          // 清空搜索框后自动触发监听器
                        },
                      )
                    : null,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
              ),
              style: const TextStyle(fontFamily: 'FangSong'),
            ),
          ),
          // 搜索结果统计
          if (_searchQuery.isNotEmpty && !_isLoading)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
              child: Text(
                '找到 ${_filteredWords.length} 个结果',
                style: const TextStyle(fontFamily: 'FangSong', color: Colors.grey),
              ),
            ),
          // 单词列表
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _errorMessage.isNotEmpty
                    ? Center(child: Text(_errorMessage, style: const TextStyle(color: Colors.red, fontFamily: 'FangSong')))
                    : _words.isEmpty
                        ? Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                const Text(
                                  '暂无单词',
                                  style: TextStyle(fontSize: 18, fontFamily: 'FangSong'),
                                ),
                              ],
                            ),
                          )
                        : _filteredWords.isEmpty && _searchQuery.isNotEmpty
                            ? Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    const Text(
                                      '未找到匹配的单词',
                                      style: TextStyle(fontSize: 18, fontFamily: 'FangSong'),
                                    ),
                                  ],
                                ),
                              )
                            : ListView.builder(
                                itemCount: _filteredWords.length,
                                itemBuilder: (context, index) {
                                  final word = _filteredWords[index];
                                  return Card(
                                    margin: const EdgeInsets.symmetric(
                                      horizontal: 16,
                                      vertical: 8,
                                    ),
                                    child: ListTile(
                                      // 多选模式下显示复选框
                                      leading: _isMultiSelectMode
                                          ? Checkbox(
                                              value: _selectedWordIds.contains(word.id),
                                              onChanged: (bool? value) {
                                                setState(() {
                                                  if (value == true) {
                                                    _selectedWordIds.add(word.id!);
                                                  } else {
                                                    _selectedWordIds.remove(word.id!);
                                                  }
                                                });
                                              },
                                            )
                                          : null,
                                      title: Text(
                                        word.word,
                                        style: GoogleFonts.roboto(fontWeight: FontWeight.bold),
                                      ),
                                      subtitle: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          if (word.pronunciation != null && word.pronunciation!.isNotEmpty)
                                            Text('读音: ${word.pronunciation}', style: GoogleFonts.notoSans()),
                                          Text('释义: ${word.meaning ?? word.translation ?? ""}', style: const TextStyle(fontFamily: 'FangSong')),
                                          if (word.example != null && word.example!.isNotEmpty)
                                            Text('例句: ${word.example}', style: const TextStyle(fontFamily: 'FangSong')),
                                          if (word.category != null && word.category!.isNotEmpty)
                                            Text('分类: ${word.category}', style: const TextStyle(fontFamily: 'FangSong')),
                                        ],
                                      ),
                                      trailing: _isMultiSelectMode
                                          ? null // 多选模式下不显示操作按钮
                                          : Row(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                // 编辑按钮
                                                IconButton(
                                                  icon: const Icon(Icons.edit, color: Colors.blue),
                                                  tooltip: '编辑',
                                                  onPressed: () async {
                                                    final result = await context.push('/word-list/edit/${word.id}');
                                                    if (result == true) {
                                                      _loadWords();
                                                    }
                                                  },
                                                ),
                                                // 删除按钮
                                                IconButton(
                                                  icon: const Icon(Icons.delete, color: Colors.red),
                                                  tooltip: '删除',
                                                  onPressed: () {
                                                    showDialog(
                                                      context: context,
                                                      builder: (context) => AlertDialog(
                                                        title: const Text('确认删除', style: TextStyle(fontFamily: 'FangSong')),
                                                        content: Text('确定要删除单词 "${word.word}" 吗？', style: const TextStyle(fontFamily: 'FangSong')),
                                                        actions: [
                                                          TextButton(
                                                            onPressed: () => Navigator.pop(context),
                                                            child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
                                                          ),
                                                          TextButton(
                                                            onPressed: () {
                                                              Navigator.pop(context);
                                                              _deleteWord(word);
                                                            },
                                                            child: const Text('删除', style: TextStyle(fontFamily: 'FangSong')),
                                                          ),
                                                        ],
                                                      ),
                                                    );
                                                  },
                                                ),
                                              ],
                                            ),
                                      // 在多选模式下，点击整个列表项可以切换选中状态
                                      onTap: _isMultiSelectMode
                                          ? () {
                                              setState(() {
                                                if (_selectedWordIds.contains(word.id)) {
                                                  _selectedWordIds.remove(word.id!);
                                                } else {
                                                  _selectedWordIds.add(word.id!);
                                                }
                                              });
                                            }
                                          : null,
                                    ),
                                  );
                                },
                              ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        heroTag: 'add_word',
        onPressed: () async {
          final result = await context.push('/word-list/add');
          if (result == true) {
            _loadWords();
          }
        },
        tooltip: '添加单词',
        child: const Icon(Icons.add),
      ),
    );
  }
}